package com.servlet;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.daofactory.DaoFactory;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.bean.User;

/**
 * @author 徐洲
 * @version 1.0
 */
@WebServlet("/admin/ImportExcelServlet")
public class ImportExcelServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException{
        String action = request.getParameter("action");

        if ("import".equals(action)) {
            importUsers(request, response);
        } else if ("export".equals(action)) {
            exportUsers(request, response);
        }
    }

    private void importUsers(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Part filePart = request.getPart("file");
        String fileName = extractFileName(filePart);

        // 保存上传的文件
        String uploadPath = getServletContext().getRealPath("") + File.separator + "uploads";
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }

        File file = new File(uploadPath + File.separator + fileName);
        try (InputStream input = filePart.getInputStream()) {
            Files.copy(input, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
        }

        // 读取Excel文件并处理数据
        try (Workbook workbook = new XSSFWorkbook(file)) {
            Sheet sheet = workbook.getSheetAt(0);
            // 遍历行和列以读取数据
            for (Row row : sheet) {
                if (row.getRowNum() == 0) continue; // 跳过标题行

                User user = new User();

                user.setUsername(row.getCell(0).getStringCellValue());
                user.setPassword(row.getCell(1).getStringCellValue());
                user.setSex(row.getCell(2).getStringCellValue());
                user.setTelephone(row.getCell(3).getStringCellValue());
                user.setEmail(row.getCell(4).getStringCellValue());

                DaoFactory.getAdminDAOInstance().saveUser(user);
            }
        } catch (InvalidFormatException e) {
            throw new RuntimeException(e);
        }
        response.sendRedirect("admin_userList.jsp");
    }

    private void exportUsers(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 从数据库检索用户数据
        List<User> userList = DaoFactory.getAdminDAOInstance().getUserList("");

        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet("Users");

            // Create header row
            Row headerRow = sheet.createRow(0);
            headerRow.createCell(0).setCellValue("Username");
            headerRow.createCell(1).setCellValue("Password");
            headerRow.createCell(2).setCellValue("Sex");
            headerRow.createCell(3).setCellValue("Telephone");
            headerRow.createCell(4).setCellValue("Email");

            // 填充数据行
            int rowNum = 1;
            for (User user : userList) {
                Row row = sheet.createRow(rowNum++);
                row.createCell(0).setCellValue(user.getUsername());
                row.createCell(1).setCellValue(user.getAvatar());
                row.createCell(2).setCellValue(user.getSex());
                row.createCell(3).setCellValue(user.getTelephone());
                row.createCell(4).setCellValue(user.getEmail());
            }

            // 设置响应标头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment; filename=users.xlsx");

            // 将工作簿数据写入响应输出流
            workbook.write(response.getOutputStream());
        }
    }

    private String extractFileName(Part part) {
        String contentDisp = part.getHeader("content-disposition");
        String[] tokens = contentDisp.split(";");
        for (String token : tokens) {
            if (token.trim().startsWith("filename")) {
                return token.substring(token.indexOf("=") + 2, token.length() - 1);
            }
        }
        return "";
    }
}
